var app = getApp();
var WxParse = require('../../lib/wxParse/wxParse.js');
var poster = require('../../common/tui-poster/tui-poster.js');
var util = require('../../utils/util.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    winWidth: 560,
    winHeight: 890,
    modalShow: false,
    modalGroupList: false,
    posterImg: '',
    height: 64, //header高度
    top: 0, //标题图标距离顶部距离
    scrollH: 0, //滚动总高度
    opcity: 0,
    iconOpcity: 0.5,
    menuShow: false,
    id: '',
    firstIndex: 0,
    goods: {},
    gallery: [],
    attribute: [],
    issueList: [],
    comment: [],
    cartGoodsCount: 0,
    userHasCollect: 0,
    number: 1,
    minNumber: 1,
    checkedSpecText: '',
    openAttr: false,
    showNavList: false,
    collectBackImage: "/static/images/icon_collect.png",
    commodityAttr: [],
    selectGroup: {}, // 选中的SKU
    keyValue: [],
    selected: '',
    selectPrice: '',
    selectGroupPrice: '',
    selectMarketPrice: '',
    selectPic: '',
    selectStock: '',
    selectGoodsSn: '',
    selectedText: '',
    includeGroup: [],
    tempQrCode: '', // 商品小程序码
    tempGoodsListPic: '', // 商品图
    shareVisible: false,
    referrerUserId: '',
    buyType: 'buySelf',
    leaderId: '', // 团长ID
    groupId: '', // 团ID
    groupList: [],
    historyTop: 130,
    couponList: [],
    bannerIndex: 0,
    modal: false,
    shippingFeeFree: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let obj = {};
    obj = wx.getMenuButtonBoundingClientRect();

    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })

    let that = this;
    //转发的用户Id
    if (options.referrer) {
      app.globalData.referrerUserId = options.referrer;
      that.data.referrerUserId = options.referrer;
    }
    wx.setStorageSync("navUrl", "/pages/groupDetail/groupDetail?id=" + options.id + "&referrer=" + that.data.referrerUserId);
    // 页面初始化 options为页面跳转所带来的参数
    that.setData({
      id: options.id
    });
    that.getGoodsInfo();
    that.getCouponList();
    that.getShippingFeeFree();

    that.setData({
      width: app.globalData.customBar.width,
      height: app.globalData.customBar.height,
      top: app.globalData.customBar.top,
      scrollH: app.globalData.customBar.scrollH
    })
  },
  onPageScroll(e) {
    let scroll = e.scrollTop <= 0 ? 0 : e.scrollTop;
    let opcity = scroll / this.data.scrollH;
    if (this.data.opcity >= 1 && opcity >= 1) {
      return;
    }
    this.setData({
      opcity: opcity,
      iconOpcity: 0.5 * (1 - opcity < 0 ? 0 : 1 - opcity)
    })
  },
  bannerChange: function (e) {
    this.setData({
      bannerIndex: e.detail.current
    });
  },
  play() {
    wx.navigateTo({
      url: '/pages/video/video?url=' + this.data.goods.videoUrl,
      animationType: 'zoom-out'
    })
  },
  moreGroup() {
    let that = this;
    that.setData({
      modalGroupList: true
    });
  },
  showModal() {
    this.setData({
      modal: true
    });
  },
  hideModal: function () {
    this.setData({
      modal: false
    })
  },
  hideModalShow: function () {
    this.setData({
      modalShow: false
    })
  },
  savePic() {
    if (this.data.posterImg) {
      poster.saveImage(this.data.posterImg);
      this.hideModalShow();
    }
  },
  coupon() {
    wx.navigateTo({
      url: '/pages/shopping/couponCenter/couponCenter'
    })
  },
  getShippingFeeFree() {
    let that = this;
    util.request('index/getTreaty', {
      type: 4
    }).then(function (res) {
      if (res.code === 0) {
        that.setData({
          shippingFeeFree: res.data
        });
      }
    });
  },
  getCouponList() {
    let that = this;
    util.request('coupon/couponList').then(function (res) {
      if (res.code === 0) {
        that.setData({
          couponList: res.data
        });
      }
    });
  },
  showShare: function () {
    this.setData({
      menuShow: false,
      shareVisible: true
    })
  },
  hideShare: function () {
    this.setData({
      shareVisible: false
    })
  },
  //放大预览轮播图片
  previewImg: function (e) {
    var curImg = e.currentTarget.dataset.img;
    var gallery = this.data.gallery;
    if (!util.isEmpty(curImg) && gallery.length > 0) {
      var urls = [];
      for (var i = 0; i < gallery.length; i++) {
        urls[i] = gallery[i].url;
      }
      wx.previewImage({
        current: curImg, // 当前显示图片的http链接
        urls: urls, // 需要预览的图片http链接列表
      })
    }
  },
  switchAttrPop: function () {
    let that = this;
    that.setData({
      openAttr: !that.data.openAttr
    });
  },
  closeAttrOrCollect: function () {
    let that = this;
    //添加或是取消收藏
    util.request('user/addOrDelete', {
      goodsId: that.id
    }, "POST").then(function (res) {
      if (res.code == 0) {
        if (res.data.type == 'add') {
          util.showMsg('收藏成功');
          that.setData({
            'collectBackImage': "/static/images/icon_collect_checked.png"
          });
        } else {
          util.showMsg('取消成功');
          that.setData({
            'collectBackImage': "/static/images/icon_collect.png"
          });
        }
      }
    });
  },
  toggleNav() {
    this.setData({
      showNavList: !this.data.showNavList
    })
  },
  back: function () {
    wx.navigateBack({
      fail() {
        wx.switchTab({
          url: '/pages/index/index',
        })
      }
    })
  },
  feedback: function () {
    wx.navigateTo({
      url: '/pages/feedback/feedback',
    })
  },
  openMenu: function () {
    this.setData({
      menuShow: true
    })
  },
  changeNumber: function (event) {
    let number = event.detail.value;
    this.setData({
      number: number
    });
  },
  closeMenu: function () {
    this.setData({
      menuShow: false
    })
  },
  pengyouquan() {
    util.showMsg('请点击右上角分享到朋友圈')
    this.setData({
      shareVisible: false
    })
  },
  switchNav(event) {
    let name = event.currentTarget.dataset.name;
    wx.switchTab({
      url: `/pages/${name}/${name}`,
    });
  },
  hideSharePopup() {
    this.setData({
      shareVisible: false
    })
  },
  openAttrModal: function (e) {
    var that = this;
    var buyType = e.currentTarget.dataset.type
    var leaderId = e.currentTarget.dataset.uid
    var groupId = e.currentTarget.dataset.id
    if (leaderId) {
      that.setData({
        leaderId: leaderId
      })
    }
    if (groupId) {
      that.setData({
        groupId: groupId
      })
    }
    that.setData({
      buyType: buyType
    })
    if (that.data.openAttr == false) {
      //打开规格选择窗口
      that.setData({
        openAttr: !that.data.openAttr,
        modalGroupList: false
      })
    }
  },
  createPoster: function () {
    let that = this
    that.hideSharePopup()
    if (that.data.posterImg) {
      that.setData({
        modalShow: true
      })
      return;
    }
    wx.showLoading({
      mask: true,
      title: '图片生成中...'
    });
    poster.removeSavedFile();

    //小程序码长宽
    let codeSize = 200;
    util.request('goods/getGroupQrCode', {
      goodsId: that.data.goods.id,
      width: codeSize
    }).then(function (resp) {
      if (resp.code === 0) {
        wx.downloadFile({
          //url网络图片地址必须要在小程序中配备合法域名
          url: resp.url,
          success(res) {
            if (res.statusCode === 200) {
              that.setData({
                tempQrCode: res.tempFilePath
              })

              const imgs = {
                mainPic: that.data.tempGoodsListPic,
                qrcode: that.data.tempQrCode
              };
              poster.drawGoodsPoster('posterId', that.data.winWidth, that.data.winHeight,
                imgs, that.data.goods.name, that.data.goods.retailPrice, that.data.goods
                .marketPrice, that.data.goods.promotionDesc || '',
                res => {
                  wx.hideLoading();
                  if (res) {
                    that.setData({
                      posterImg: res
                    })
                    setTimeout(() => {
                      that.setData({
                        modalShow: true
                      })
                    }, 60);
                  } else {
                    util.showMsg('生成海报失败,请稍后再试');
                  }
                });
            }
          }
        })
      }
    });
  },
  getGoodsInfo: function () {
    let that = this;
    util.request('goods/otherDetail', {
      goodsId: that.data.id,
      userId: wx.getStorageSync('userId') || ''
    }).then(function (res) {
      if (res.code === 0) {
        that.setData({
          issueList: res.data.issue,
          comment: res.data.comment,
          userHasCollect: res.data.userHasCollect
        });
        if (res.data.userHasCollect == 1) {
          that.setData({
            'collectBackImage': "/static/images/icon_collect_checked.png"
          });
        } else {
          that.setData({
            'collectBackImage': "/static/images/icon_collect.png"
          });
        }
      }
    });
    util.request('goods/detail', {
      goodsId: that.data.id,
      userId: wx.getStorageSync('userId') || ''
    }).then(function (res) {
      if (res.code === 0) {
        that.setData({
          goods: res.data.info,
          minNumber: res.data.info.minSell || 1,
          number: res.data.info.minSell || 1,
          gallery: res.data.info.attachmentEntityList,
          attribute: res.data.info.goodsAttributeEntityList,
          selectPrice: res.data.info.retailPrice,
          selectPic: res.data.info.listPicUrl,
          selectGoodsSn: res.data.info.goodsSn,
          selectGroupPrice: res.data.info.groupPrice,
          selectMarketPrice: res.data.info.marketPrice,
          selectStock: res.data.info.goodsNumber,
          selectGoodsSn: res.data.info.goodsSn
        });
        wx.downloadFile({
          //url网络图片地址必须要在小程序中配备合法域名
          url: that.data.goods.listPicUrl,
          success(res) {
            if (res.statusCode === 200) {
              that.setData({
                tempGoodsListPic: res.tempFilePath
              })
            }
          }
        })
        that.setData({
          commodityAttr: res.data.info.goodsSkuEntityList,
          includeGroup: res.data.info.goodsSkuEntityList
        })
        that.distachAttrValue(that.data.commodityAttr);
        // 只有一个属性组合的时候默认选中
        // console.log(this.data.keyValue);
        if (that.data.commodityAttr.length == 1) {
          for (var i = 0; i < that.data.commodityAttr[0].keyValue.length; i++) {
            that.data.keyValue[i].selectedValue = that.data.commodityAttr[0].keyValue[i].value;
          }
          that.setData({
            keyValue: that.data.keyValue
          });
        }
        WxParse.wxParse('goodsDetail', 'html', res.data.info.goodsDesc, that);
      }
      that.setSelect();
    });
    util.request('cart/goodsCount', {
      userId: wx.getStorageSync('userId') || ''
    }).then(function (res) {
      if (res.code === 0) {
        that.setData({
          cartGoodsCount: res.goodsCount
        });
      }
    });
  },

  buyOrCartAdd: function () {
    var that = this;
    var value = [];
    for (var i = 0; i < that.data.keyValue.length; i++) {
      if (that.data.keyValue[i].selectedValue && that.data.keyValue[i].attrValueStatus[that.data.keyValue[i].selectedIndex]) {
        value.push(that.data.keyValue[i].selectedValue);
      }
    }
    if (value.length < that.data.keyValue.length) {
      util.showMsg('请选择完整！');
    } else {
      if (!that.data.includeGroup[0]) {
        util.showMsg('商家暂未添加商品规格！');
        return;
      }
      // 单独购买
      if (that.data.buyType == 'buySelf') {
        // 直接购买商品
        util.request('buy/add', {
          skuId: that.data.selectGroup.id,
          goodsId: that.data.goods.id,
          number: that.data.number,
          selectedText: that.data.selectedText
        }, "POST", 'application/json').then(function (res) {
          let _res = res;
          if (_res.code == 0) {
            that.setData({
              openAttr: !that.data.openAttr
            });
            wx.navigateTo({
              url: '/pages/shopping/checkout/checkout?isBuy=true',
            })
          }
        });
      }
      // 发起拼团
      if (that.data.buyType == 'startGroup' || that.data.buyType == 'joinGroup') {
        util.request('buy/addGroup', {
          skuId: that.data.selectGroup.id,
          goodsId: that.data.goods.id,
          number: that.data.number,
          selectedText: that.data.selectedText,
          groupId: that.data.groupId,
          leaderId: that.data.leaderId
        }, "POST", 'application/json').then(function (res) {
          let _res = res;
          if (_res.code == 0) {
            that.setData({
              openAttr: !that.data.openAttr
            });
            wx.navigateTo({
              url: '/pages/groupCheckout/groupCheckout?groupId=' + that.data.groupId
            })
          }
        });
      }
    }
  },
  /* 获取数据 */
  distachAttrValue: function (commodityAttr) {
    /**
    将后台返回的数据组合成类似
    {
    key:'型号',
    keyValue:['1','2','3']
    }
    */
    // 把数据对象的数据（视图使用），写到局部内
    var keyValue = this.data.keyValue;
    // 遍历获取的数据
    for (var i = 0; i < commodityAttr.length; i++) {
      for (var j = 0; j < commodityAttr[i].keyValue.length; j++) {
        var attrIndex = this.getAttrIndex(commodityAttr[i].keyValue[j].key, keyValue);
        // console.log('属性索引', attrIndex);
        // 如果还没有属性索引为-1，此时新增属性并设置属性值数组的第一个值；索引大于等于0，表示已存在的属性名的位置
        if (attrIndex >= 0) {
          // 如果属性值数组中没有该值，push新值；否则不处理
          if (!this.isValueExist(commodityAttr[i].keyValue[j].value, keyValue[attrIndex].attrValues)) {
            keyValue[attrIndex].attrValues.push(commodityAttr[i].keyValue[j].value);
          }
        } else {
          keyValue.push({
            key: commodityAttr[i].keyValue[j].key,
            attrValues: [commodityAttr[i].keyValue[j].value]
          });
        }
      }
    }
    // console.log('result', keyValue)
    for (var i = 0; i < keyValue.length; i++) {
      for (var j = 0; j < keyValue[i].attrValues.length; j++) {
        if (keyValue[i].attrValueStatus) {
          keyValue[i].attrValueStatus[j] = true;
        } else {
          keyValue[i].attrValueStatus = [];
          keyValue[i].attrValueStatus[j] = true;
        }
      }
    }
    this.setData({
      keyValue: keyValue
    });
  },
  getAttrIndex: function (attrName, keyValue) {
    // 判断数组中的attrKey是否有该属性值
    for (var i = 0; i < keyValue.length; i++) {
      if (attrName == keyValue[i].key) {
        break;
      }
    }
    return i < keyValue.length ? i : -1;
  },
  isValueExist: function (value, valueArr) {
    // 判断是否已有属性值
    for (var i = 0; i < valueArr.length; i++) {
      if (valueArr[i] == value) {
        break;
      }
    }
    return i < valueArr.length;
  },
  /* 选择属性值事件 */
  selectAttrValue: function (e) {
    /*
    点选属性值，联动判断其他属性值是否可选
    {
    key:'型号',
    keyValue:['1','2','3'],
    selectedValue:'1',
    attrValueStatus:[true,true,true]
    }
    console.log(e.currentTarget.dataset);
    */
    var keyValue = this.data.keyValue;
    var index = e.currentTarget.dataset.index; //属性索引
    var key = e.currentTarget.dataset.key;
    var value = e.currentTarget.dataset.value;
    var valueindex = e.currentTarget.dataset.vi;
    if (e.currentTarget.dataset.status || index == this.data.firstIndex) {
      if (e.currentTarget.dataset.selectedvalue == e.currentTarget.dataset.value) {
        // 取消选中
        this.disSelectValue(keyValue, index, key, value, valueindex);
      } else {
        // 选中
        this.selectValue(keyValue, index, key, value, valueindex);
      }
    }
  },
  /* 选中 */
  selectValue: function (keyValue, index, key, value, valueindex) {
    var includeGroup = [];
    keyValue[index].selectedValue = value;
    keyValue[index].selectedIndex = valueindex;

    var commodityAttr = this.data.includeGroup;
    for (var i = 0; i < commodityAttr.length; i++) {
      for (var j = 0; j < commodityAttr[i].keyValue.length; j++) {
        if (commodityAttr[i].keyValue[j].key == key && commodityAttr[i].keyValue[j].value == value) {
          includeGroup.push(commodityAttr[i]);
        }
      }
    }

    // 判断属性是否可选
    for (var i = 0; i < keyValue.length; i++) {
      for (var j = 0; j < keyValue[i].attrValues.length; j++) {
        keyValue[i].attrValueStatus[j] = false;
      }
    }
    for (var i = 0; i < includeGroup.length; i++) {
      var flag = includeGroup[i].keyValue.every(function (ikv, ikvIndex) {
        if (keyValue[ikvIndex].key === ikv.key) {
          return keyValue[ikvIndex].selectedValue === ikv.value
        }
        return true;
      })
      // 所有key-value对都命中
      if (flag) {
        this.setData({
          selectGroup: includeGroup[i]
        });
      }
      for (var k = 0; k < keyValue.length; k++) {
        for (var j = 0; j < includeGroup[i].keyValue.length; j++) {
          if (keyValue[k].key == includeGroup[i].keyValue[j].key) {
            for (var m = 0; m < keyValue[k].attrValues.length; m++) {
              if (keyValue[k].attrValues[m] == includeGroup[i].keyValue[j].value || (includeGroup[i].keyValue[j].key == key && includeGroup[i].keyValue[j].value == value)) {
                keyValue[k].attrValueStatus[m] = true;
              }
            }
          }
        }
      }
    }
    this.setData({
      keyValue: keyValue
    });

    var count = 0;
    for (var i = 0; i < keyValue.length; i++) {
      for (var j = 0; j < keyValue[i].attrValues.length; j++) {
        if (keyValue[i].selectedValue) {
          count++;
          break;
        }
      }
    }
    if (count < 2) { // 第一次选中，同属性的值都可选
      this.setData({
        firstIndex: index
      });
    } else {
      this.setData({
        firstIndex: -1
      });
    }
    this.setSelect();
  },
  /* 取消选中 */
  disSelectValue: function (keyValue, index, key, value, valueindex) {
    var that = this;
    var commodityAttr = that.data.commodityAttr;
    keyValue[index].selectedValue = '';
    keyValue[index].selectedIndex = '';

    // 判断属性是否可选
    for (var i = 0; i < keyValue.length; i++) {
      for (var j = 0; j < keyValue[i].attrValues.length; j++) {
        keyValue[i].attrValueStatus[j] = true;
      }
    }
    that.setData({
      includeGroup: commodityAttr,
      keyValue: keyValue,
      selectGroup: {}
    });

    for (var i = 0; i < keyValue.length; i++) {
      if (keyValue[i].selectedValue) {
        that.selectValue(keyValue, i, keyValue[i].key, keyValue[i].selectedValue, valueindex);
      }
    }
    that.setSelect();
  },
  setSelect: function () {
    var that = this;
    var valueStr = "";
    var value = [];
    var selectedText = '';
    for (var i = 0; i < that.data.keyValue.length; i++) {
      if (that.data.keyValue[i].selectedValue && that.data.keyValue[i].attrValueStatus[that.data.keyValue[i].selectedIndex]) {
        value.push(that.data.keyValue[i].selectedValue);
        selectedText += that.data.keyValue[i].key + '：' + that.data.keyValue[i].selectedValue + '；'
      }
    }
    for (var i = 0; i < value.length; i++) {
      valueStr += value[i] + ",";
    }
    valueStr = valueStr.substr(0, valueStr.length - 1)
    that.setData({
      selected: valueStr
    })
    if (!that.data.selectGroup.id) {
      that.setData({
        selectPrice: that.data.goods.retailPrice,
        selectStock: that.data.goods.goodsNumber,
        selectPic: that.data.goods.listPicUrl,
        selectGoodsSn: that.data.goods.goodsSn,
        selectGroupPrice: that.data.goods.groupPrice,
        selectMarketPrice: that.data.goods.marketPrice,
        selectedText: selectedText
      })
      return;
    }
    that.setData({
      selectPrice: that.data.selectGroup.retailPrice,
      selectStock: that.data.selectGroup.goodsNumber,
      selectPic: that.data.selectGroup.listPicUrl,
      selectGroupPrice: that.data.selectGroup.groupPrice,
      selectMarketPrice: that.data.selectGroup.marketPrice,
      selectGoodsSn: that.data.selectGroup.goodsSn,
      selectedText: selectedText
    })
  },
  previewSkuImg(e) {
    wx.previewImage({
      urls: [e.currentTarget.dataset.url], // 需要预览的图片http链接列表
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  onShareTimeline: function () {
    var that = this;

    let shareDesc = that.data.goods.name;
    let goods = that.data.goods;
    shareDesc += ' ' + goods.retailPrice + "元";
    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title: shareDesc, // 默认是小程序的名称(可以写slogan等)
      path: '/pages/goods/goods?id=' + that.data.id + '&&referrer=' + wx.getStorageSync('userId'), // 默认是当前页面，必须是以‘/’开头的完整路径
      //query: 'id=' + that.data.id + '&referrer=' +wx.getStorageSync('userId'),
      imageUrl: that.data.goods.listPicUrl, //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {
          util.showMsg('转发成功');
        }
      },
      fail: function () {
        // 转发失败之后的回调
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          // 用户取消转发
        } else if (res.errMsg == 'shareAppMessage:fail') {
          // 转发失败，其中 detail message 为详细失败信息
        }
      },
      complete: function () {
        // 转发结束之后的回调（转发成不成功都会执行）
      }
    };
    return shareObj;
  },
  onShareAppMessage: function () {
    var that = this;
    let shareDesc = that.data.goods.name;
    let goods = that.data.goods;
    shareDesc += ' ' + goods.retailPrice + "元";
    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title: shareDesc, // 默认是小程序的名称(可以写slogan等)
      desc: "商业版",
      path: '/pages/groupDetail/groupDetail?id=' + that.data.id + '&&referrer=' + wx.getStorageSync('userId'), // 默认是当前页面，必须是以‘/’开头的完整路径
      imageUrl: that.data.goods.listPicUrl, //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {
          util.showMsg('转发成功');
        }
      },
      fail: function () {
        // 转发失败之后的回调
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          // 用户取消转发
        } else if (res.errMsg == 'shareAppMessage:fail') {
          // 转发失败，其中 detail message 为详细失败信息
        }
      },
      complete: function () {
        // 转发结束之后的回调（转发成不成功都会执行）
      }
    };
    return shareObj;
  }
})
